import router from '../routes';
import { ElMessage } from "element-plus"

function arrayDiff(arr1, arr2) {
	let arrOne = [], arrTwo = [], diffArr = [], resp = [];
	arr1.forEach(item => {
		arrOne.push(JSON.stringify(item))
	})
	arr2.forEach(item => {
		arrTwo.push(JSON.stringify(item))
	})
	arrOne.forEach(itemA => {
		if (arrTwo.indexOf(itemA) === -1) {
			diffArr.push(itemA)
		}
	})
	diffArr.forEach(itemD => {
		resp.push(JSON.parse(itemD))
	})
	return resp;
}

function imageValidate(file) {
	const extendName = file.name.split(".")[1];
	const isJPEG = extendName === "jpeg";
	const isJPG = extendName === "jpg";
	const isPNG = extendName === "png";
	const isGIF = extendName === "gif";
	const sizeValidate = file.size / 1024 / 1024 < 2;
	if (!isJPG && !isJPEG && !isPNG && !isGIF) {
		this.$message.error("上传图片只能是 JPEG/JPG/PNG/GIF 格式!");
	}
	if (!sizeValidate) {
		this.$message.error("单张图片大小不能超过 2MB!");
	}
	return (isJPEG || isJPG || isPNG || isGIF) && sizeValidate;
}

function formatDateTime(dateObj = null, time = false) {
	if (!dateObj) dateObj = new Date();
	// 获取年、月、日、小时、分钟和秒数
	var year = dateObj.getFullYear(), 									// 2021
		month = (dateObj.getMonth() + 1).toString().padStart(2, '0'), 	// 09
		day = dateObj.getDate().toString().padStart(2, '0'); 			// 30
	let date = `${year}-${month}-${day}`
	if (time) {
		return `${date} ${time}`
	}
	var hours = dateObj.getHours().toString().padStart(2, '0'), 		// 15
		minutes = dateObj.getMinutes().toString().padStart(2, '0'),		// 47
		seconds = dateObj.getSeconds().toString().padStart(2, '0'); 	// 36

	// 构造格式化后的日期和时间字符串
	return `${date} ${hours}:${minutes}:${seconds}`;
}

function getTimeRangeOptions() {
	const dayTime = 3600 * 24 * 1000;
	const today = new Date(),
		curDate = today.getDay(),
		yestaday = new Date(),
		week = new Date(),
		lastWeek = new Date();

	yestaday.setDate(yestaday.getDate() - 1);
	week.setTime(week.getTime() - curDate * dayTime);
	lastWeek.setDate(lastWeek.getDate() - 7);
	lastWeek.setTime(lastWeek.getTime() - curDate * dayTime);
	const lastWeekEnd = new Date(week.getTime() - dayTime);

	return [
		{ text: '今日', value: [tools.formatDateTime(today, '00:00:00'), tools.formatDateTime(today, '23:59:59')] },
		{ text: '昨日', value: [tools.formatDateTime(yestaday, '00:00:00'), tools.formatDateTime(yestaday, '23:59:59')] },
		{ text: '本周', value: [tools.formatDateTime(week, '00:00:00'), tools.formatDateTime(today, '23:59:59')] },
		{ text: '上周', value: [tools.formatDateTime(lastWeek, '00:00:00'), tools.formatDateTime(lastWeekEnd, '23:59:59')] },
	]
}

function httpFaildHandler(res, type = 'error') {
	let errMsg = '请求失败，请稍后再试';
	if (res && res['message']) errMsg = res.message;
	ElMessage({ type: type, message: errMsg })
}


function getTypeName(cType, gType) {
	switch (cType) {
		case 1:
			return '单牌类型';
		case 2:
			return '对子类型';
		case 3:
			return '两对类型';
		case 4:
			return '三条类型';
		case 5:
			return '顺子类型';
		case 6:
			if (gType > 210040)
				return '葫芦类型'
			return '同花类型';
		case 7:
			if (gType > 210040)
				return '同花类型';
			return '葫芦类型';
		case 8:
			if (gType > 210040)
				return '四条类型';
			return '铁支类型';
		case 9:
			return '同花顺型';
		case 10:
			return '皇家同花顺';
	}
}

function ipValidator(ip){
	return /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/.test(ip);
}


const tools = {
	toLogin() {
		router.replace('/login')
	},
	orderVerify: (rule, value, callback) => {
		if (parseInt(value) > 30000) {
			callback(new Error('排序值不能大于30000'));
		} else {
			callback();
		}
	},
	numberVerify: (rule, value, callback) => {
		if (!rule.required && !value) {
			callback();
			return;
		}
		if (/^([1-9][0-9]*|0)(\.[0-9]?[1-9])?$/.test(value)) {
			callback();
		} else {
			callback(new Error('请输入正确的正数（正整数与小数，小数点不得超过2位）'));
		}
	},
	urlVerify: (rule, value, callback) => {
		// 先检查是否为必填项
		if (!rule.required && !value) {
			callback();
			return;
		}
		// （是必填项||内容不为空） 才进行匹配
		if (/^(http|https|ftp):\/\/[\w\-]+(\.[\w\-]+)*([\w\-\.,@$?^=%&:/~\+#]*[\w\-\@$?^=%&/~\+#])?$/.test(value)) {
			callback();
		} else {
			callback(new Error('请输入正确的网络链接'));
		}
	},
	phoneVerify: (rule, value, callback) => {
		if (!rule.required && !value) {
			callback();
			return;
		}
		if (/^1[3-9]\d{9}?$/.test(value)) {
			callback();
		} else {
			callback(new Error('请输入正确的手机号码'));
		}
	},
	multipleVerify: (rule, value, callback) => {
		if (!rule.required && !value) {
			callback();
			return;
		}
		if (!value || value.length < 1) {
			callback(new Error('请选择'));
		} else {
			callback();
		}
	},
	uploadPrefix: (app) => {
		if (app.$adminer.info.isRelease) {
			return '/images/';
		}
		return '/dev/images/';
	},
	arrayDiff,
	deepCopy(obj) {
		return JSON.parse(JSON.stringify(obj))
	},
	loadQueries(queries, query, sizeOptions = []) {
		for (const key in query) {
			if (queries.hasOwnProperty(key)) {
				query[key] = queries[key];
			}
		}
		if (queries.page) query.page = parseInt(queries.page);
		if (queries.size) {
			query.size = parseInt(queries.size);
			if (sizeOptions.indexOf(queries.size) !== false) {
				query.size = queries.size;
			}
		}
		return query;
	},
	getTypeName,
	ipValidator,
	imageValidate,
	formatDateTime,
	getTimeRangeOptions,
	httpFaildHandler,
}

export default tools;